import { useState, useEffect, useCallback } from 'react'
import { View, Text } from '@tarojs/components'
import Loading from '../component/load'
import Taro, { useTabItemTap } from '@tarojs/taro'
import { getStorage } from '@/pages/components/utils/index'
import { HttpGet, HttpPost, HttpDelete, HttpPut } from '@/network/servers'
import Utils from '@/utils/index'
// import PrTableDay from '../component/tableDay'
import ScheduleTable from '../scheduleTable'
// import ScheduleTable from '../scheduleTable1'
import dayjs from 'dayjs'
import { Calendar } from 'react-h5-calendar'
import _, { has } from 'lodash'
import { getBrowserController } from '@/pages/components/utils'
import { connect, useDispatch } from "react-redux";
import { LgPopLayer } from "lancoo-ui-mobile";
import './index.scss'
import ScheduleTime from '../scheduleTime'
const storage = getStorage()
const {
  getNowToken,
  recentDateStr,
  getDate
} = Utils

var wx = require('weixin-js-sdk')

const browserController = getBrowserController()
let InfoObj = {} as any

function App(props) {

  const {
    userInfo,
    env,
    lg_ic,
    baseUrl,
    mainServer,
    setYearMonth,
    yearMonth,
    setTypeNum,
    typeNum,
  } = props

  const [scheduleList, setScheduleList] = useState<any>([])
  const [loadVisible, setLoadVisible] = useState(true)

  const [currentDate, setCurrentDate] = useState(dayjs().format('YYYY-MM-DD'))//当天日期
  const [startDate, setStartDate] = useState('')//日历当月第一天
  const [endDate, setEndDate] = useState('')//日历当月最后一天
  const [hasScheduleArr, setHasScheduleArr] = useState([])
  const [allDayList, setAllDayList] = useState([])
  // 2025-1-15增加年视图定制
  const [timeList, setTimeList] = useState([
    {
      check: true,
      type: '按周显示',
      value: 0,
    },
    {
      check: false,
      type: '按月显示',
      value: 1,
    },
    {
      check: false,
      type: '按年显示',
      value: 2,
    }
  ])
  const [isOpen, setIsOpen] = useState(false);
  const [monthList, setMonthList] = useState([]);
  const [yearList, setYearList] = useState([])
  const [yearNum, setYearNum] = useState(0)

  const handleLayer = useCallback(() => {
    setIsOpen(!isOpen);
  }, [isOpen]);

  useEffect(() => {
    if (typeNum == 0) {
      checkTime(0);
    }
  }, [typeNum])

  const checkTime = (index) => {
    setTimeList(prevTimeList =>
      prevTimeList.map((item, idx) => ({
        ...item,
        check: idx === index, // 只有当索引匹配时，check才为true
      }))
    );
    setTypeNum(index);
    setIsOpen(false);
  }

  const gobackToday = () => {
    setCurrentDate(dayjs().format('YYYY-MM-DD'));
    setTimeList([
      {
        check: true,
        type: '按周显示',
        value: 0,
      },
      {
        check: false,
        type: '按月显示',
        value: 1,
      },
      {
        check: false,
        type: '按年显示',
        value: 2,
      }
    ])
    setIsOpen(false);
  }

  const getToken = () => {
    if (Utils.getQueryVariable('env') === 'weapp') {
      return Utils.getQueryVariable('lg_tk')
    } else {
      return storage.get('token') || Utils.getQueryVariable('lg_tk')
    }
  }

  // 获取整年个人日程列表
  const getScheduleYearList = () => {
    HttpGet({
      url: `/api/schedule/list/person`,
      data: {
        userId: userInfo.userId,
        userType: userInfo.userType,
        eduId: userInfo.eduId,
        startTime: dayjs(currentDate).get("year") + '-01-01',
        endTime: dayjs(currentDate).get("year") + '-12-31',
      },
      load: true
    }).then((result) => {
      if (result.code === '200' && Array.isArray(result.data)) {
        let data = result.data;
        setYearList(data);
      }
    })
  }

  // 获取整月个人日程列表
  const getScheduleMonthList = (callback: any = null, start = startDate, end = endDate) => {
    HttpGet({
      url: `/api/schedule/list/person`,
      data: {
        userId: userInfo.userId,
        userType: userInfo.userType,
        eduId: userInfo.eduId,
        startTime: start,
        endTime: end,
      },
      load: true
    }).then((result) => {
      if (result.code === '200' && Array.isArray(result.data)) {
        let data = result.data;
        setMonthList(data);
        let hasScheduleArr = []
        data.forEach(element => {
          if (hasScheduleArr.indexOf(element.scheduleDate) == -1) {
            hasScheduleArr.push(element.scheduleDate);
          }
        });
        let arr = [];
        hasScheduleArr.forEach(item => {
          arr.push({ date: item })
        })
        setHasScheduleArr(arr);
        setLoadVisible(false);
        if (callback) {
          setTimeout(() => {
            callback()
          }, 500);
        }
      }
    })
  }

  // 获取个人日程列表
  const getScheduleList = () => {
    HttpGet({
      url: `/api/schedule/list/person`,
      data: {
        userId: userInfo.userId,
        userType: userInfo.userType,
        eduId: userInfo.eduId,
        startTime: currentDate,
        endTime: currentDate,
      },
      load: true
    }).then((result) => {
      if (result.code === '200') {
        setScheduleList(result.data);
        setYearNum(yearNum + 1);
        let arr = [];
        result.data && result.data.map(item => {
          if (item.beAllDay == 1) {
            arr.push(item);
          }
        })
        setAllDayList(arr);
        // setLoadVisible(false);
      }
    })
  }
  //路由返回当前页面并刷新
  Taro.useDidShow(() => {
    // window.location.reload();
    setTimeout(() => {
      getScheduleList();
      getScheduleMonthList();
      getScheduleYearList();
    }, 200);
  })

  const jumpWeapp = (appId, path) => {
    try {
      browserController.navigateToMiniProgramForWebview(wx, {
        appId,//必传 跳转小程序唯一标识
        path,//必传 跳转后初始页面路径
        extraData: {},
        envVersion: 'release',//必传 跳转小程序的版本
      })
    } catch (err) {
      Taro.showToast({ title: err, icon: 'none' })
    }
  }

  // 跳转发布页面
  const goCreate = (data) => {
    let url = '/pages/scheduleApp/createSchedule/index?id='
    if (data) {
      url += '?id=' + data.scheduleId + ' &lg_tk=' + Utils.getQueryVariable('lg_tk') + '&lg_ic=' + Utils.getQueryVariable('lg_ic')
    }
    Taro.navigateTo({
      url
    })
  }

  //跳转详情页
  const goDetail = (data) => {
    console.log(data, 'data11');
    let url = '';
    // if (data.beCourse == 1) return;
    if (data.isCreate === 1) {
      let start = data.startTime1
      let end = data.endTime1
      url = '/pages/scheduleApp/createSchedule/index?startDate=' + currentDate + '&start=' + start + '&end=' + end
    } else {
      if (data.beCourse == 1) {
        url = '/pages/scheduleApp/courseDetail/index?beCourse=' + data.beCourse + '&class=' + (data.class ? data.class : '无') + '&title=' + data.scheduleContent + '&address=' + (data.scheduleLocation ? data.scheduleLocation : '无')
          + '&scheduleDate=' + data.scheduleDate + '&startTime=' + data.startTime1 + '&endTime=' + data.endTime1 + '&times=' + data.times
      } else {
        url = '/pages/scheduleApp/scheduleDetail/index?id=' + data.scheduleId
      }
    }
    Taro.navigateTo({
      url
    })
  }

  useEffect(() => {
    getScheduleList();
  }, [currentDate,])

  useEffect(() => {
    if (Utils.getQueryVariable('isFromOther') == '1') {
      let id = Utils.getQueryVariable('id');
      if (!id) return;
      let schedule = {
        scheduleId: id
      }
      goDetail(schedule);
    }
  }, [])

  useEffect(() => {
    console.log(yearMonth, 'yearMonth')
    if (dayjs(yearMonth).format('YYYY-MM-DD').indexOf('2') >= 0) {
      setStartDate(dayjs(yearMonth).startOf('month').format('YYYY-MM-DD'));
      setEndDate(dayjs(yearMonth).endOf('month').format('YYYY-MM-DD'));
      console.log(yearMonth, 'yearMonth', dayjs(yearMonth).format('YYYY-MM-DD'), startDate);
    }
  }, [yearMonth])
  useEffect(() => {
    if (startDate && endDate) {
      getScheduleMonthList();
      getScheduleYearList();
    }
  }, [startDate, endDate])
  let arr = [];
  const [selectedDate, setSelectedDate] = useState(new Date());
  // 设置可选时间范围为从今天开始的未来10天
  const minDate = new Date();
  const maxDate = new Date();
  maxDate.setDate(maxDate.getDate() + 10);
  // 标记可选时间范围
  const markTime = (date) => {
    return date >= minDate && date <= maxDate;
  };
  // 禁用不可选时间范围
  const disabledTime = (date) => {
    return date < minDate || date > maxDate;
  };

  const selectMonth = (month, day, date) => {
    setCurrentDate(dayjs(date).format('YYYY-MM-01'))
    let start = dayjs(date).startOf('month').format('YYYY-MM-DD')
    let end = dayjs(date).endOf('month').format('YYYY-MM-DD')
    getScheduleMonthList(
      setTimeList(
        [
          {
            check: false,
            type: '按周显示',
            value: 0,
          },
          {
            check: true,
            type: '按月显示',
            value: 1,
          },
          {
            check: false,
            type: '按年显示',
            value: 2,
          }
        ]
      ),
      start,
      end,
    )
  }
  const timeType = timeList.find(item => item.check)?.value;
  return (
    <View className='schedule-contanier'>
      <View className='time_select'>
        <View className='time_view'>{dayjs(currentDate).format('YYYY年M月')}</View>
        <View className='time_type_select' onClick={() => handleLayer()}>
          <View className='time_select_type'>{timeList.find(item => item.check)?.type}</View>
          <View className='time_select_icon'></View>
        </View>
      </View>
      <LgPopLayer
        position="bottom"
        isOpen={isOpen}
        showLayer={handleLayer}
        showClose
        title="选择视图"
        className='time_list_popLayer'
        titleContainerClass='time_list_popLayer_title'
        titleClass='popLayer_title'
        closeIconClass='popLayer_icon'
        insideContentClass='popLayer_Content'
        customContentClass='popLayer_customContent'
      >
        <View className="time_list_view">
          <View className='back_today' onClick={() => gobackToday()}>回到今天</View>
          {
            timeList.map((item, index) => {
              return (
                <View className='time_list_item' onClick={() => checkTime(index)}>
                  <View className='time_item_name'>{item.type}</View>
                  <View className={'time_item_icon ' + (item.check ? 'item_check_icon' : '')}></View>
                </View>
              )
            })
          }
        </View>
      </LgPopLayer>
      {timeType !== 0 ?
        <View className='calendar_view'>
          <ScheduleTime yearNum={yearNum} key={yearNum} timeType={timeType} currentDate={currentDate} scheduleList={monthList} yearList={yearList} selectMonth={selectMonth}></ScheduleTime>
        </View>
        : ''
      }

      {timeType === 0 ?
        <View className='days-option'>
          <View className='days-select'>
            <View className='calendar'>
              <Calendar
                onDateClick={(date) => setCurrentDate(date.format('YYYY-MM-DD'))}
                showType={'week'}
                markDates={hasScheduleArr}
                markType="dot"
                currentDate={currentDate}
                onTouchEnd={(a, b) => console.log(dayjs(a).format('YYYY-MM-DD'), dayjs(b).format('YYYY-MM-DD'), '11221')}
                setYearMonth={setYearMonth}
              />
            </View>
          </View>
          <View className='days-schedule'>
            {allDayList.length > 0 ?
              <View className='days-schedule-all'>全天</View> : ''
            }
            <View className={allDayList.length > 0 ? 'days-schedule-item' : ''}>
              {
                scheduleList.length > 0 ?
                  scheduleList.map((item, index) => {
                    if (item.beAllDay == '1') {
                      return (
                        <Text className='days-schedule-text' onClick={() => goDetail(item)}>{item.scheduleTitle}</Text>
                      )
                    }
                  })
                  : ''
              }
            </View>
          </View>
        </View>
        : ''
      }
      <Loading mode="center" content="加载中..." isOpened={loadVisible}></Loading>
      {timeType === 0 ?
        <View className='table-box'>
          {/* <PrTableDay datalist={scheduleList} onClickItem={(item) => goDetail(item)}></PrTableDay> */}
          <ScheduleTable datalist={scheduleList} onClickItem={(item) => goDetail(item)} date={currentDate} ></ScheduleTable>
        </View>
        : ''
      }

      {/* 创建+ */}
      <View className='create-schedule-button' onClick={() => goCreate('')}></View>
      <i className='create-shadow'></i>
    </View>
  )
}


const mainProps = ({ commonData }) => {
  return {
    userInfo: commonData.userInfo,
    env: commonData.env,
    baseUrl: commonData.baseUrl,
    mainServer: commonData.mainServer,
    lg_ic: commonData.lg_ic
  }
}

export default connect(mainProps)(App)